// pages/lovecarlife/lovecarlife.js
const app = getApp();
var util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabList: ['今日推荐', '车趣杂谈', '车友生活', '香车美女'],
    currentTabIndex: 0,
    swiperList0: [], //今日推荐
    swiperList1: [], //车群杂谈
    swiper3: null, //香车美女
    interval: true,
    duration: 3000,
    previousMargin: '30rpx',
    nextMargin: '30rpx',
    avatarArr: [], //随机头像  范围【1-15】
    tabSpaceHeight: 0, //tab展位高度
    isNoMore: false, //是否还有数据   
    isShowLoad: false, //是否显示底部loading组件
    comments: [], //内容列表
    pageIndex: 1, //页索引
    pageSize: 5, //页大小
    defaultImg: '/images/default-750-360.jpg'
  },
  // methods: {
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    //tab的高度
    wx.createSelectorQuery().select('#tab').boundingClientRect(function (rect) {
      self.setData({
        tabSpaceHeight: rect.height // 节点的高度
      })
    }).exec();

    //如果是分享H5页面进入
    if (options.shareUrl) {
      let url = options.shareUrl;
      app.globalData.shareUrl = options.shareUrl;
      app.globalData.isShare = true;
      // 这里需要判断一下当前用户是否已经登录，登录则跳转到指定页面，没有登录则跳转到登录页
      let query = '?webUrl=' + encodeURIComponent(url);
      wx.navigateTo({
        url: '/pages/webView/webView' + query
      })
    }

    //加载数据
    self.getArticleData();

    self.getBannerList();

    //随机头像
    let avatarIndex = null;
    let avatarArr = [];
    for (let i = 0; i < 5; i++) {
      avatarIndex = Math.ceil(Math.random() * 10 + 5);
      avatarArr.push(app.globalData.apiImgUrl + 'beauty/beauty' + avatarIndex + '.jpg');
    }
    self.setData({
      avatarArr: avatarArr
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let self = this;
    app.getSession();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let self = this;
    console.log('下拉刷新');
    self.reset(); //重置
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let self = this;
    // console.log('onReachBottom')
    if (self.data.isNoMore) {
      return;
    }
    self.data.pageIndex++;
    self.getArticleData(); //加载更多
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.globalData.shareInfo;
  },
  /**
   * 重置所有
   */
  reset: function () {
    let self = this;
    //今日推荐和车趣杂谈每页5条，其他10条
    let pageSize = 5;
    if (self.data.currentTabIndex > 1) {
      pageSize = 10;
    }
    self.setData({
      isNoMore: false, //是否还有数据   
      isShowLoad: false, //是否显示底部loading组件
      comments: [], //内容列表
      pageIndex: 1, //页码
      pageSize: pageSize, //页大小
    });
    if (self.data.currentTabIndex == 2) {
      self._doClearMasonry('mainWaterfall');
    } else if (self.data.currentTabIndex == 3) {
      self._doClearMasonry('subWaterfall');
    }

    self.getArticleData(); //获取文章第一页数据
  },
  /**
   * 获取数据
   */
  getArticleData: function () {
    let self = this;
    let url = app.globalData.apiRootUrl + "/Comment/GetCommentList";
    let type = self.data.currentTabIndex;
    let isHot = -1;

    let data = {
      PageSize: self.data.pageSize,
      PageIndex: self.data.pageIndex,
      OpenID: app.globalData.userInfo.OpenID,
      Section: type, //1：车趣杂谈 2：车友生活 3.香车美女
      IsHot: type == 0 ? 1 : -1 //0：今日推荐
    };

    self.setData({
      isShowLoad: true //显示底部loading组件
    })

    app.httpRequest({
      url: url,
      data: data,
      success: function (res) {
        //console.log('文章', res);
        let rdata = res.data;
        if (rdata.status == 0 && rdata.data.rows) {
          let comments = self.data.comments;
          //兼容有头图和没有头图两种情况
          for (let i = 0; i < rdata.data.rows.length; i++) {
            if (!util.isNullOrEmpty(rdata.data.rows[i].HeadImgUrl)) {
              let tmp = {
                ImageUrl: rdata.data.rows[i].HeadImgUrl,
                ImageSort: 1
              };
              rdata.data.rows[i].CommentImgs = [tmp];
            }
          }
          comments = comments.concat(rdata.data.rows);
          self.setData({
            comments: comments
          });
          switch (type) {
            case 0:
            case 1:
              break;
            case 2:
              self._doAppendMasonry(rdata.data.rows, 'mainWaterfall');
              break;
            case 3:
              self._doAppendMasonry(rdata.data.rows, 'subWaterfall');
              break;
          }
        }

        //如果返回的数据长度小于页大小，则说明没有数据了
        if (rdata.data.rows.length < self.data.pageSize) {
          self.setData({
            isShowLoad: true,
            isNoMore: true // true 没有数据了  false  还有数据
          });
        } else {
          self.setData({
            isShowLoad: false //今日推荐是否显示底部loading组件
          });
        }
      },
      fail: function (err) {
        console.log('获取第一页数据失败');
        self.setData({
          isShowLoad: false //今日推荐是否显示底部loading组件
        });
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    })
  },
  /**
   * tab点击切换
   */
  tabTap: function (e) {
    let self = this;
    console.log(e);
    let index = e.currentTarget.dataset.index;
    if (self.data.currentTabIndex == index) {
      return;
    }
    self.setData({
      currentTabIndex: index
    });
    self.reset();
    self.getBannerList();
  },
  _doRefreshMasonry(items, id) {
    // this.mainWaterfallComponent = this.selectComponent('#mainWaterfall');
    this.waterfallComponent = this.selectComponent('#' + id);
    this.waterfallComponent.start(items).then(() => {
      console.log('refresh completed');
    })
  },
  /**
   * 追加瀑布流
   */
  _doAppendMasonry(items, id) {
    this.waterfallComponent = this.selectComponent('#' + id);
    // 获取接口数据后使用瀑布流组件append方法，当append完成后调用then，是否可触底价在的标志位可以在这里处理
    this.waterfallComponent.append(items).then(() => {
      console.log('refresh completed')
    })
  },
  /**
   * 清空瀑布流
   */
  _doClearMasonry(id) {
    this.waterfallComponent = this.selectComponent('#' + id);
    this.waterfallComponent.clear();
  },
  likeTopTap: function () {
    let self = this;
    if (self.data.swiper3) {
      self.data.swiper3.isLike = true;
      self.data.swiper3.PraiseCount++;
      self.setData({
        swiper3: self.data.swiper3
      });

      self.addLike(self.data.swiper3.CommentID);
    }
  },
  //点赞
  likeTap(e) {
    let self = this;
    let id = e.detail.id || 0;
    let isWater = true;
    if (id < 1) {
      isWater = false;
      id = e.currentTarget.dataset.id;
    }
    let list = self.data.comments;
    let index = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i].CommentID == id) {
        index = i;
        if (list[i].isLike) {
          return;
        } else {
          list[i].PraiseCount++;
          list[i].isLike = true;

          self.addLike(id);
          break;
        }
      }
    }
    self.setData({
      comments: list
    })
    if (isWater) {
      let typeid = e.currentTarget.dataset.typeid;
      self.waterfallComponent = self.selectComponent('#' + typeid);
      self.waterfallComponent.updateItem(list[index], index).then(() => {
        console.log('更新完成');
      })
    }
  },
  /**
   * 点赞统计
   */
  addLike: function (id) {
    let self = this;
    let url = app.globalData.apiRootUrl + "/WxUser/WxUserTrailRecord";
    app.httpRequest({
      url: url,
      method: "POST",
      data: {
        UserID: app.globalData.userInfo.UserID,
        TrailIdentity: id,
        TrailType: 2, //浏览类型(1:产品 2：名片 3：文章 4：趣味问答,5：小程序，6：小游戏)
        ActionType: 5, //操作类别(1：转发 2：浏览 3：答题 4：评论 5：点赞，6：取消点赞)
        OpenID: app.globalData.userInfo.OpenID,
        UnionID: app.globalData.userInfo.UnionID,
      },
      success: function (res) {}
    })
  },
  //去往详情页面
  goToDetail(e) {
    let self = this;
    let id = e.detail.id || 0;
    if (id < 1) {
      id = e.currentTarget.dataset.commentid;
    }
    let query = 'commentID=' + id;
    console.log(query)
    wx.navigateTo({
      url: 'articleDetail/articleDetail?' + query,
    })
  },
  /**
   * 获取头图列表
   */
  getBannerList: function () {
    let self = this;
    let url = "";
    let data = {};
    let type = self.data.currentTabIndex; //1:今日推荐  2：车趣杂谈 3：车友生活 4.香车美女
    switch (type) {
      case 0:
        url = app.globalData.apiRootUrl + "/Common/GetBannerList";
        data = {
          category: type + 1
        };
        if (self.data.swiperList0.length > 0) {
          return;
        }
        break;
      case 1:
        data = {
          category: type + 1
        };
        url = app.globalData.apiRootUrl + "/Common/GetBannerList";
        if (self.data.swiperList1.length > 0) {
          return;
        }
        break;
      case 2:
        return;
        break;
      case 3:
        url = app.globalData.apiRootUrl + "/Comment/GetTop";
        data = {
          Section: 3, //1：车趣杂谈 2：车友生活 3.香车美女
        };
        if (self.data.swiper3 != null) {
          return;
        }
        break;
    }
    // console.log(url);

    app.httpRequest({
      url: url,
      data: data,
      success: function (res) {
        //console.log('文章', res);
        let rdata = res.data;
        if (rdata.status == 0 && rdata.data) {
          switch (type) {
            case 0:
              self.setData({
                swiperList0: rdata.data
              })
              break;
            case 1:
              self.setData({
                swiperList1: rdata.data
              })
              break;
            case 3:
              self.setData({
                swiper3: rdata.data
              })
              break;
          }
        }
      },
      fail: function (err) {
        console.log('获取第一页数据失败');

      },
      complete: function () {

      }
    })
  },
  /**
   * 跳转到详情
   */
  bannerTap: function (e) {
    if (e.currentTarget.dataset.lurl) {
      let query = encodeURIComponent(e.currentTarget.dataset.lurl);
      wx.navigateTo({
        url: '/pages/webView/webView?webUrl=' + query
      });
    }
  }
})